package com.platform.qujia.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;

/**
 * <Title> PosPrinterUtil </Title>
 * <Description> Pos机打印订单小票工具类 </Description>
 * <Date> 2021年5月6日16:49:40 </Date>
 * <Author> JK </Author>
 */
@Component
public class PosPrinterUtil {

    private static Logger logger =(Logger) LoggerFactory.getLogger(PosPrinterUtil.class);

    //生产环境： http://www.huijy.net/mqapi/sendPosPrintDirectMessage
    //public static final String SEND_POS_PRINT_MESSAGE_URL = "http://www.huijy.net/mqapi/sendPosPrintFanoutMessage";

    //测试环境：http://mp.huijy.net/mqapi/sendPosPrintFanoutMessage
    //public static final String SEND_POS_PRINT_MESSAGE_URL = "http://mp.huijy.net/mqapi/sendPosPrintFanoutMessage";
    public static  String domainName;

    @Value("${qujia.domainName}")
    public void setDomainName(String doMain){
        this.domainName = doMain;
    }


    //推送要打印小票的信息
    public static String sendPosPrintDirectMessage(Map<String, Object> args){
        //创建请求
        CloseableHttpClient httpClients = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString ="";
        try {
            // 创建Http Post请求
            String SEND_POS_PRINT_MESSAGE_URL = "http://"+domainName+"/mqapi/sendPosPrintFanoutMessage";
            HttpPost httpPost = new HttpPost(SEND_POS_PRINT_MESSAGE_URL);
            logger.info("POS推送订单消息地址：" +SEND_POS_PRINT_MESSAGE_URL);
            // 创建请求内容
            StringEntity entity = new StringEntity(JSONObject.toJSONString(args), ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClients.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            logger.info("POS推送订单消息结果：" +resultString);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("POS推送订单消息异常信息:"+e.getMessage());
        }finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }
}
